package socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * 客户端
 * <p>
 * 站在客户端的角度, 五元组
 * 源IP: 自己
 * 源端口号: 系统分配
 * 目的IP: 服务器的IP, 127.0.0.1
 * 目的端口: 服务器的端口,9090
 * 协议: UDP
 */
public class UDPDictClient {
    //1. 创建socket
    //2. 发送数据
    DatagramSocket socket = null;
    String serverIp;
    int serverPort;

    public UDPDictClient(String serverIp, int serverPort) throws SocketException {
        socket = new DatagramSocket();// 不指定端口号, 系统随机分配
        this.serverIp = serverIp;
        this.serverPort = serverPort;

    }
    public void start() throws IOException {
        //发送数据
        System.out.println("客户端已启动...");
        Scanner scanner = new Scanner(System.in);
        /**
         * void send(DatagramPacket p)
         *
         * DatagramPacket  发送的数据报, 数据报中要指明目的IP和端口
         *
         * DatagramPacket(byte buf[], int offset, int length,
         *                           InetAddress address, int port)
         *  参数说明:
         *  buf: 发送的数据的byte数组
         *  offset: 从数组的某一位开始发送
         *  length: 发送的数据长度
         *  address: IP
         *  port: 端口号
         */
        while (true){
            System.out.println("请输入要发送的内容:");
            String request = scanner.nextLine();//从控制台接收一个数据

            DatagramPacket packet = new DatagramPacket(request.getBytes(),0,
                    request.getBytes().length, InetAddress.getByName(serverIp),serverPort );
            socket.send(packet);

            //接收响应
            byte[] buf = new byte[1024];
            DatagramPacket responsePacket = new DatagramPacket(buf,buf.length);
            socket.receive(responsePacket);
            //解析并打印出来
            String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8");
            System.out.printf("发送数据:%s,接收到数据:%s\n",request,response);
        }

    }

    public static void main(String[] args) throws IOException {
        UDPDictClient client = new UDPDictClient("127.0.0.1",9090);
        client.start();
    }

}
